const yargs = require('yargs/yargs');
const { hideBin } = require('yargs/helpers');
const axios = require('axios');
const fs = require('fs');
const path = require('path');
const inquirer = require('inquirer'); // 确保正确引入 inquirer

const argv = yargs(hideBin(process.argv))
  .default('host', '127.0.0.1')
  .default('port', 8080)
  .command('login', 'Login to the server', () => {}, async (argv) => {
    const answers = await inquirer.prompt([
      {
        type: 'input',
        name: 'user',
        message: 'Enter username:',
        default: 'zs'
      },
      {
        type: 'password',
        name: 'pwd',
        message: 'Enter password:',
        default: 'ddd'
      }
    ]);

    try {
      const response = await axios.post(`http://${argv.host}:${argv.port}/login`, {
        username: answers.user,
        password: answers.pwd
      });
      console.log('Login successful. Session ID:', response.data.sessionId);
      argv.sessionId = response.data.sessionId; // Save the session ID for future commands
    } catch (error) {
      console.error('Login failed:', error.response.data.error);
    }
  })
  .command('upload <file>', 'Upload a file', () => {}, async (argv) => {
    if (!argv.sessionId) {
      console.error('Please login first.');
      return;
    }
    try {
      const data = fs.readFileSync(argv.file, 'base64');
      const response = await axios.post(`http://${argv.host}:${argv.port}/upload`, {
        filename: path.basename(argv.file),
        data
      }, {
        headers: { 'session-id': argv.sessionId }
      });
      console.log(response.data.message);
    } catch (error) {
      console.error('Upload failed:', error.response.data.error);
    }
  })
  .command('download <file>', 'Download a file', () => {}, async (argv) => {
    if (!argv.sessionId) {
      console.error('Please login first.');
      return;
    }
    try {
      const response = await axios.get(`http://${argv.host}:${argv.port}/download/${argv.file}`, {
        headers: { 'session-id': argv.sessionId },
        responseType: 'arraybuffer'
      });
      fs.writeFileSync(argv.file, response.data);
      console.log('Download successful.');
    } catch (error) {
      console.error('Download failed:', error.response.data.error);
    }
  })
  .command('delete <file>', 'Delete a file', () => {}, async (argv) => {
    if (!argv.sessionId) {
      console.error('Please login first.');
      return;
    }
    try {
      const response = await axios.delete(`http://${argv.host}:${argv.port}/delete/${argv.file}`, {
        headers: { 'session-id': argv.sessionId }
      });
      console.log(response.data.message);
    } catch (error) {
      console.error('Delete failed:', error.response.data.error);
    }
  })
  .command('rename <oldFile> <newFile>', 'Rename a file', () => {}, async (argv) => {
    if (!argv.sessionId) {
      console.error('Please login first.');
      return;
    }
    try {
      const response = await axios.put(`http://${argv.host}:${argv.port}/rename`, {
        oldFilename: argv.oldFile,
        newFilename: argv.newFile
      }, {
        headers: { 'session-id': argv.sessionId }
      });
      console.log(response.data.message);
    } catch (error) {
      console.error('Rename failed:', error.response.data.error);
    }
  })
  .command('mkdir <dir>', 'Create a directory', () => {}, async (argv) => {
    if (!argv.sessionId) {
      console.error('Please login first.');
      return;
    }
    try {
      const response = await axios.post(`http://${argv.host}:${argv.port}/mkdir`, {
        dirname: argv.dir
      }, {
        headers: { 'session-id': argv.sessionId }
      });
      console.log(response.data.message);
    } catch (error) {
      console.error('Mkdir failed:', error.response.data.error);
    }
  })
  .command('rmdir <dir>', 'Remove a directory', () => {}, async (argv) => {
    if (!argv.sessionId) {
      console.error('Please login first.');
      return;
    }
    try {
      const response = await axios.delete(`http://${argv.host}:${argv.port}/rmdir/${argv.dir}`, {
        headers: { 'session-id': argv.sessionId }
      });
      console.log(response.data.message);
    } catch (error) {
      console.error('Rmdir failed:', error.response.data.error);
    }
  })
  .command('list', 'List directory contents', () => {}, async (argv) => {
    if (!argv.sessionId) {
      console.error('Please login first.');
      return;
    }
    try {
      const response = await axios.get(`http://${argv.host}:${argv.port}/list`, {
        headers: { 'session-id': argv.sessionId }
      });
      console.log(response.data.contents);
    } catch (error) {
      console.error('List failed:', error.response.data.error);
    }
  })
  .command('lcd <dir>', 'Change local directory', () => {}, (argv) => {
    try {
      process.chdir(argv.dir);
      console.log('Local directory changed to:', process.cwd());
    } catch (error) {
      console.error('LCD failed:', error.message);
    }
  })
  .command('lpwd', 'Print local directory', () => {}, () => {
    console.log('Local directory:', process.cwd());
  })
  .command('rcd <dir>', 'Change remote directory', () => {}, async (argv) => {
    if (!argv.sessionId) {
      console.error('Please login first.');
      return;
    }
    try {
      const response = await axios.put(`http://${argv.host}:${argv.port}/rcd`, {
        dirname: argv.dir
      }, {
        headers: { 'session-id': argv.sessionId }
      });
      console.log(response.data.message);
    } catch (error) {
      console.error('RCD failed:', error.response.data.error);
    }
  })
  .command('rpwd', 'Print remote directory', () => {}, async (argv) => {
    if (!argv.sessionId) {
      console.error('Please login first.');
      return;
    }
    try {
      const response = await axios.get(`http://${argv.host}:${argv.port}/rpwd`, {
        headers: { 'session-id': argv.sessionId }
      });
      console.log('Remote directory:', response.data.dirname);
    } catch (error) {
      console.error('RPWD failed:', error.response.data.error);
    }
  })
  .parse();

if (!argv._ || argv._.length === 0) {
  console.log('Usage: node client.js <command> [options]');
  console.log('Use --help for more information.');
}